import { useEffect, useState, useRef } from "react";
import { Image as AntdImage, Skeleton } from "antd";

export default function ProxyImage({ originalUrl = null, style, alt = "" }) {
  const [showSkeleton, setShowSkeleton] = useState(true);
  const [finalUrl, setFinalUrl] = useState(null);
  const loadingTimeout = useRef(null);

  useEffect(() => {
    let isActive = true;
    let img = new Image();
    let fallbackImg = new Image();

    const startLoading = () => {
      // 只有请求超过50ms还没完成才显示骨架屏
      loadingTimeout.current = setTimeout(() => {
        setShowSkeleton(true);
      }, 50);
    };

    const completeLoading = () => {
      clearTimeout(loadingTimeout.current);
      setShowSkeleton(false);
    };

    const loadWithFallback = async () => {
      try {
        startLoading();

        // 先尝试原始URL
        const originalLoaded = await new Promise((resolve) => {
          img.onload = () => resolve(true);
          img.onerror = () => resolve(false);
          img.src = originalUrl;
        });

        if (!originalLoaded) {
          // 原始URL失败，尝试代理URL
          const proxyUrl = `https://images.weserv.nl/?url=${encodeURIComponent(
            originalUrl
          )}`;
          await new Promise((resolve) => {
            fallbackImg.onload = () => resolve(true);
            fallbackImg.onerror = () => resolve(false);
            fallbackImg.src = proxyUrl;
          });
        }

        if (isActive) {
          setFinalUrl(originalLoaded ? originalUrl : fallbackImg.src);
          completeLoading();
        }
      } catch {
        if (isActive) {
          setFinalUrl(null);
          completeLoading();
        }
      }
    };

    loadWithFallback();

    return () => {
      isActive = false;
      clearTimeout(loadingTimeout.current);
      img.onload = img.onerror = null;
      fallbackImg.onload = fallbackImg.onerror = null;
    };
  }, [originalUrl]);

  return (
    <div
      key={originalUrl}
      style={{
        position: "relative",
        ...style,
        display: originalUrl ? "block" : "none",
      }}>
      {showSkeleton && (
        <Skeleton.Avatar
          active
          style={{
            position: "absolute",
            top: 0,
            left: 0,
            width: "100%",
            height: "100%",
            borderRadius: style?.borderRadius || 4,
          }}
          shape="square"
        />
      )}

      {finalUrl && (
        <AntdImage
          src={finalUrl}
          alt={alt}
          style={{
            width: "100%",
            height: "100%",
            borderRadius: style?.borderRadius || 4,
            objectFit: "cover",
            opacity: showSkeleton ? 0 : 1,
            transition: showSkeleton ? "none" : "opacity 0.2s ease-out",
            ...style,
          }}
          preview={false}
          onLoad={() => {
            clearTimeout(loadingTimeout.current);
            setShowSkeleton(false);
          }}
          onError={() => {
            clearTimeout(loadingTimeout.current);
            setShowSkeleton(false);
          }}
        />
      )}
    </div>
  );
}
